package com.qf.smartplatform.controller;

import com.qf.smartplatform.dto.R;
import com.qf.smartplatform.events.UserLoginEvent;
import com.qf.smartplatform.exceptions.LoginException;
import com.qf.smartplatform.pojo.User;
import com.qf.smartplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/users")
public class UserController {

    private ApplicationContext context;
    private UserService userService;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    @PostMapping("/user")
    public R registry(@RequestBody User user){
        userService.addUser(user);
        return R.setOK();
    }
    @PostMapping("/login")
    public R login(String username, String password, HttpSession session) {
        try {
            User user = userService.login(username, password);
            session.setAttribute("user", user);
            context.publishEvent(new UserLoginEvent(R.setOK(user.getUsername())));
            return R.setOK(user.getUsername());
        } catch (Exception e) {
            context.publishEvent(new UserLoginEvent(R.setError(0, "登陆失败")));
            throw new LoginException("登陆失败", 0);
        }
    }
}
